package com.unittec.zk.provider.exam.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.unittec.zk.provider.exam.utils.BeanMapper;
import com.unittec.zk.sdk.exam.domain.QuAnswerDTO;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unittec.zk.provider.exam.entity.ElQuAnswer;
import com.unittec.zk.provider.exam.mapper.ElQuAnswerMapper;
import org.springframework.util.CollectionUtils;

@Service
public class ElQuAnswerService extends ServiceImpl<ElQuAnswerMapper, ElQuAnswer> {

    /**
     * 保存答案
     *
     * @param quId
     * @param list
     */
    public void saveAll(String quId, List<QuAnswerDTO> list) {
        //最终要保存的列表
        List<ElQuAnswer> saveList = new ArrayList<>();

        //已存在的标签列表
        List<String> ids = this.findExistsList(quId);

        if (!CollectionUtils.isEmpty(list)) {
            for (QuAnswerDTO item : list) {

                //标签ID
                String id = item.getId();
                ElQuAnswer answer = new ElQuAnswer();
                BeanMapper.copy(item, answer);
                answer.setQuId(quId);

                //补全ID避免新增
                if (ids.contains(id)) {
                    ids.remove(id);
                }
                saveList.add(answer);
            }

            //保存标签列表
            if (!CollectionUtils.isEmpty(saveList)) {
                this.saveOrUpdateBatch(saveList);
            }

            //删除已移除
            if (!ids.isEmpty()) {
                this.removeByIds(ids);
            }
        } else {

            QueryWrapper<ElQuAnswer> wrapper = new QueryWrapper<>();
            wrapper.lambda().eq(ElQuAnswer::getQuId, quId);
            this.remove(wrapper);
        }
    }


    /**
     * 查找已存在的列表
     *
     * @param quId
     * @return
     */
    public List<String> findExistsList(String quId) {
        //返回结果
        List<String> ids = new ArrayList<>();

        QueryWrapper<ElQuAnswer> wrapper = new QueryWrapper();
        wrapper.lambda().eq(ElQuAnswer::getQuId, quId);
        List<ElQuAnswer> list = this.list(wrapper);

        if (!CollectionUtils.isEmpty(list)) {
            for (ElQuAnswer item : list) {
                ids.add(item.getId());
            }
        }
        return ids;
    }

    public List<ElQuAnswer> listAnswerByRandom(String quId) {
        QueryWrapper<ElQuAnswer> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(ElQuAnswer::getQuId, quId);
        wrapper.last(" ORDER BY RAND() ");

        return this.list(wrapper);
    }
}
